#!/usr/bin/ruby -w
# -* coding: UTF-8 -*-

################################################################################
# Copyright 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
################################################################################
require 'shardeddb'

SHARD_NUM = 50
HOST_PATTERN = 'dbhost%d'
DB_PATTERN = 'db%d'

##
# SINGLE_SHARD example. Queries a single shard for data.
##
db1 = ShardedDb.new(ShardedDb::QueryType::SINGLE_SHARD, 'user', 'password',
    HOST_PATTERN, DB_PATTERN, SHARD_NUM)
# Connect to shard 2
db1.connect(2)
puts 'Connected to shard'
# Get all user IDs on the shard
results1 = db1.query('select Id from Users;')
results1.each do |line|
  puts line['Users.Id']
end
# Disconnect from the shard
db1.disconnect

##
# ALL_SHARDS example. Gets the youngest user in every shard.
##
db2 = ShardedDb.new(ShardedDb::QueryType::ALL_SHARDS, 'user', 'password',
    HOST_PATTERN, DB_PATTERN, SHARD_NUM)
# Connect to all shards (simultaneously)
db2.connect
puts 'Connected to all shards'
# Get Id and name for youngest user in every shard
results2 = db2.query('select Id, Name from Users order by Age desc limit 1;')

results2.each_with_index do |line, shard|
  puts "Shard #{shard}: #{line['Users.Name']} (Id #{line['Users.Id']}"
end
# Disconnect from all shards
db2.disconnect

##
# UNKNOWN_SHARD example. Finds a specific user and gets their data.
##
db3 = ShardedDb.new(ShardedDb::QueryType::UNKNOWN_SHARD, 'user', 'password',
    HOST_PATTERN, DB_PATTERN, SHARD_NUM)
# Get name for user
results3_name = db3.query('select Name from Users where Id = 1000;')
# Get notes for this user
results3_notes = db3.query(
    'select Title, Details from Notes where UserId = 1000;')

puts "Notes for #{results3_name[0]['Users.Name']}:"
results3_notes.each do |line|
  puts "Title: #{line['Notes.Title']}"
  puts "Details: #{line['Notes.Details']}"
  puts "---"
end
# Disconnects from the single shard that's still connected
db3.disconnect
